<template>
    <div class="logLogin_block">
        <div class="top">
            <search-bar v-model="searchModel" :search-data="searchData" :config="searchData" @search="handleSearchSubmit"
                @searchReset="handleSearchReset" style="margin-top:0;margin-left:-20px;padding-top:.2rem">
            </search-bar>
        </div>

        <div class="bottom">

            <div class="btn_area" size="medium">
                <el-button type="primary" size="medium" @click="add">新增</el-button>
                <el-dropdown @command="handleCommand" style="margin-left: 0.1rem">
                    <el-button size="medium">
                        批量操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="import">启用</el-dropdown-item>
                        <el-dropdown-item command="export">禁用</el-dropdown-item>
                        <!-- <el-dropdown-item command="check">查重</el-dropdown-item> -->
                    </el-dropdown-menu>
                </el-dropdown>
                <el-button type="" size="medium" style="margin-left: 0.1rem" @click="exportWay">导出</el-button>
            </div>
            <LPTablePage :show-index="true" :table-data="tableData" :table-column="tableColumn" :total="total"
                :current-page="currentPage" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"
                :selection="true" @handleSelectionChange="handleSelectionChange" ref="tablePage" :selectable="selectable">
                <template slot="isEnabled" slot-scope="scope">
                    <el-switch v-model="scope.row.isEnabled" active-value="1" inactive-value="0"></el-switch>
                </template>


            </LPTablePage>
        </div>
        <base-dialog :visible="addVisile" :title="(isEdit ? '编辑' : '新增') + '司机'" width="918px" class="addDictDialog"
            @handleDialogSubmit="handleAddSubmit" @handleDialogCancle="handleAddCancle">
            <el-form ref="dictForm" :model="dictModel" :rules="ruleRule" label-width="120px" class="dictForm"
                label-position="top" size="medium">
                <el-row :gutter="50">

                    <el-col :span="12">
                        <el-form-item label="姓名:" prop="name">
                            <el-input v-model.trim="dictModel.name" placeholder="请输入">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号:" prop="phone">
                            <el-input v-model.trim="dictModel.phone" placeholder="请输入">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="关联用户帐号:" prop="">
                            <el-select style="width:100%" v-model="dictModel.linkedUserAccount"
                                :remote-method="getAccountQueryListWay" filterable default-first-option remote
                                placeholder="请选择">
                                <el-option v-for="(item) in accountQueryList" :key="item.id"
                                    :label="item.phone" :value="item.phone" :disabled="item.isbindDriver==1"/>
                            </el-select>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="身份证号:" prop="idCardNumber">
                            <el-input v-model="dictModel.idCardNumber" placeholder="请输入">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="驾驶证号:" prop="drivingLicenseNumber">
                            <el-input v-model="dictModel.drivingLicenseNumber" placeholder="请输入">
                            </el-input>
                        </el-form-item>
                    </el-col>


                </el-row>

                <el-row :gutter="50">
                    <el-col :span="12">
                        <!-- <el-form-item label="身份证照片:" prop=""> -->
                            <div style="display:flex;">
                                <div class="tac">
                                    <el-form-item label="人像面" prop="idCardPhotoFace">
                                            <imageUpload v-model="dictModel.idCardPhotoFace" :isShowTip="false" />
                                        </el-form-item>
                                 
                                </div>
                                <div class="ml20 tac">
                                    <el-form-item label="国徽面" prop="idCardPhotoBack">
                                            <imageUpload v-model="dictModel.idCardPhotoBack" :isShowTip="false" />
                                        </el-form-item>
                                   
                                </div>

                            </div>
                            <div>
                                支持扩展名：.png .jpg .jpeg；单个文件大小不超过500MB
                            </div>
         
                        <!-- </el-form-item> -->
                    </el-col>
                    <el-col :span="12">
                      
                            <div style="display:flex;">
                                <div class="tac">
                                    <el-form-item label="主页" prop="drivingLicensePhotoMain">
                                            <imageUpload v-model="dictModel.drivingLicensePhotoMain" :isShowTip="false" />
                                        </el-form-item>
                                 
                                </div>
                                <div class="ml20 tac">
                                    <el-form-item label="副页" prop="drivingLicensePhotoSecondary">
                                            <imageUpload v-model="dictModel.drivingLicensePhotoSecondary" :isShowTip="false" />
                                        </el-form-item>
                                   
                                </div>

                            </div>
                            <div>
                                支持扩展名：.png .jpg .jpeg；单个文件大小不超过500MB
                            </div>
                      
                    </el-col>
                </el-row>
                <el-row :gutter="50">
                    <el-col :span="12">
                        <el-form-item label="是否启用:" prop="isEnabled">

                            <el-switch v-model="dictModel.isEnabled" />
                            <span class="ml20">关闭后司机无法执行计划</span>

                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </base-dialog>
    </div>
</template>
    
<script>
import { validateNumber } from "@/utils/validate";
import baseDialog from '@/components/BaseDialog'
import SearchBar from '@/components/SearchBar'
import LPTablePage from '@/components/LPTablePage'
import {
    logininforList,
    delLogininfor,
    cleanLogininfor
} from '@/api/system/logs'
import beiGangApi from '@/api/logistics/beigang'

import { addDateRange } from "@/utils/ruoyi";

export default {
    name: "driver",
    components: {
        LPTablePage, SearchBar, baseDialog
    },
    data() {
        const validateNumberF = (rule, value, callback) => {
            if (Number(value) == 0) {
                return callback(new Error("不能为0"));
            }
            if (!validateNumber(value)) {
                return callback(new Error("请输入正确数字"));
            } else {
                callback();
            }
        };
        const validateEmpty = (rule, value, callback) => {
            console.log('validateEmpty', value, value instanceof Array);
            if (!(value instanceof Array)) {
                return callback(new Error("必填"));
            }
            if (value instanceof Array && value.length == 0) {
                return callback(new Error("必填"));
            } else {
                callback()
            }
        };
        return {
            addVisile: false,
            isEdit: false,
            dictModel: {
                idCardPhotoFace: null,
                idCardPhotoBack: null,
                drivingLicensePhotoMain: null,
                drivingLicensePhotoSecondary: null,
                name: '',
                idCardNumber: '',
                drivingLicenseNumber: '',
                isEnabled: true,
            },
            searchModel: {},
            searchData: [
                { placeholder: "司机姓名", prop: "name", },
                { placeholder: "身份证号", prop: "idCardNumber" },
                {
                    prop: 'isEnabled',
                    type: 'select',
                    placeholder: '是否启用',
                    options: [
                        { label: '未启用', value: '0' },
                        { label: '启用', value: '1' },

                    ]
                },

                {

                    label: "注册时间", prop: "createTime", type: "daterangehms",
                    startPlaceholder: "起始时间",
                    endPlaceholder: "结束时间",
                    span: 6
                },
                {
                    label: "创建时间", prop: "updateTime", type: "daterangehms",
                    startPlaceholder: "起始时间",
                    endPlaceholder: "结束时间",
                    span: 6
                },
                {
                    prop: 'search',
                    type: 'button',
                    policy: ['system.log.query'],
                },
            ],
            tableData: [],
            tableColumn: [
                { label: "司机姓名", prop: "name", },

                { label: "关联用户账号", prop: "linkedUserAccount" },
                { label: "手机号", prop: "phone", },
                { label: "是否启用", prop: "isEnabled", render: true },
                { label: "驾驶证号", prop: "drivingLicenseNumber", },

                { label: "注册时间", prop: "createTime", },



                { label: "操作时间", prop: "updateTime", },


                {
                    label: '操作',
                    prop: 'action',
                    fixed: 'right',
                    type: 'button',
                    width: 170,
                    buttons: [
                        {
                            label: '查看',
                            type: 'text',
                            color: 'rgba(0, 118, 255, 1)',
                            method: 'handleDetail',
                        },
                        {
                            label: '编辑',
                            type: 'text',
                            color: 'rgba(0, 118, 255, 1)',
                            method: 'handleEdit',

                        },
                        {
                            label: '删除',
                            type: 'text',
                            color: '#ee3333',
                            method: 'handleDelete',

                        },
                    ],
                },

                //  {
                //     label: "操作",
                //     prop: "action",
                //     type: "button",
                //     hideTooLtip:true,
                //     width:180,
                //     button:[
                //         {
                //             label: "查看",
                //             type: "text",
                //             icon: "el-icon-view",
                //             method:`_detail${this.$options.name}`
                //         },
                //         {
                //             label: "通过",
                //             type: "text",
                //             icon: "el-icon-view",
                //             hide:'isCanTakeAudit',
                //             // hide:'canTakeAudit',
                //             hideValue:[false],
                //             policy:['Crm.CluePoolManage.TakeAudit'],
                //             method:`_auditSuccess${this.$options.name}`
                //         },
                //         {
                //             label: "驳回",
                //             type: "text",
                //             icon: "el-icon-view",
                //             hide:'isCanTakeAudit',
                //             // hide:'canTakeAudit',
                //             hideValue:[false],
                //             policy:['Crm.CluePoolManage.TakeAudit'],
                //             method:`_auditFail${this.$options.name}`
                //         },
                //     ]
                //  }   
            ],
            total: 0,
            currentPage: 1,
            selectArr: [],
            allotVisile: false,
            allotModel: {},
            allotRule: {
                responsibleUserId: [
                    // { required: true, trigger: "blur", message: "必填" },
                    { validator: validateEmpty, required: true, trigger: "blur" }
                ],
            },
            userOptions: [],
            settingVisile: false,
            ruleModel: {},
            ruleRule: {
                name: [
                    { required: true, trigger: "blur", message: "必填" }
                ],
                phone: [
                    { required: true, trigger: "blur", message: "必填" }
                ],
                idCardNumber: [
                    { required: true, trigger: "blur", message: "必填" }
                ],
                drivingLicenseNumber: [
                    { required: true, trigger: "blur", message: "必填" }
                ],
                idCardPhotoFace: [
                    { required: true, trigger: "change", message: "必填" }
                ],
                idCardPhotoBack: [
                    { required: true, trigger: "change", message: "必填" }
                ],
                drivingLicensePhotoMain:[
                    { required: true, trigger: "change", message: "必填" }
                ],
                drivingLicensePhotoSecondary:[
                    { required: true, trigger: "change", message: "必填" }
                ],
                autoRecycleEnable: [{ required: true, trigger: "blur", message: "必填" }],
                autoRecycleByNotFollowUpOverDays: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" }],

                originalResponsibleUserTakeLimit: [{ required: true, trigger: "blur", message: "必填" }],
                originalResponsibleUserTakeLimitDays: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" },
                ],
                takeLimit: [{ required: true, trigger: "blur", message: "必填" }],
                takeLimitByEveryDayNumbers: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" },
                ],
            },
            detailVisible: false,
            detailId: '',
            openSeaClueId: '',
            status: null,
            isCanTakeAudit: null,
            accountQueryList:[],
        }
    },
    mounted() {
        this.getLogininforList()
        // 消息详情
        this.$bus.$on('handleDetail', rows => {
            this.$router.push({ path: `/logistics/beiGang/driverDetail/${rows.id}` })
        })
        // 消息详情
        this.$bus.$on('handleEdit', rows => {

            beiGangApi.getDriverDetail(rows.id).then(res => {

                if (res.code == 200) {
                    this.dictModel = {
                        ...res.data,
                        idCardPhotoFace: [{
                            url: res.data.idCardPhotoFace
                        }],
                        idCardPhotoBack: [{
                            url: res.data.idCardPhotoBack
                        }],
                        drivingLicensePhotoMain: [{
                            url: res.data.drivingLicensePhotoMain
                        }],
                        drivingLicensePhotoSecondary: [{
                            url: res.data.drivingLicensePhotoSecondary
                        }],

                        isEnabled: res.data.isEnabled == 1 ? true : false
                    }
                    this.isEdit = true
                    this.addVisile = true
                }
            })
        })
        // 删除消息
        this.$bus.$on('handleDelete', rows => {
            this.$confirm('确定删除吗', '删除', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {
                //   console.log('确认');
                // let params = {
                //     ids: this.selectArr.map(item => item.id),
                // }
                beiGangApi.delDriver(rows.id).then(res => {
                    if (!res.error) {
                        this.$message.success("操作成功")
                        this.getLogininforList()
                        this.$refs.tablePage.clearSelection()
                    }
                })
            })
        })
    },
    methods: {
        handleCommand(val) {
            if (this.selectArr.length == 0) {
                this.$message.warning("请先勾选")
                return
            } else {
                const len = this.selectArr.length
                let title = '启用'
                let content = '确定要启用吗？'

                switch (val) {
                    // 启用
                    case 'import':
                        if (len >= 2) {
                            title = '批量启用'
                            content = `已选择${len}项，确定要启用吗？`
                        }
                        this.setEnabled(
                            {
                                isEnabled: 1,
                                content,
                                title,
                            }
                        )
                        break;

                    default:
                        title = '禁用'
                        content = '确定要禁用吗？'
                        if (len >= 2) {
                            title = '批量禁用'
                            content = `已选择${len}项，确定要禁用吗？`
                        }
                        this.setEnabled(
                            {
                                isEnabled: 0,
                                content,
                                title,
                            }
                        )
                        break;
                }
            }

        },

        // 启用操作
        setEnabled(obj) {
            let params = {
                ids: this.selectArr.map(item => item.id).join(','),
                isEnabled: obj.isEnabled
            }


            this.$confirm(obj.content, obj.title, {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {

                beiGangApi.setDriverEditEnabled(params).then(res => {
                    if (!res.error) {
                        this.$message.success("操作成功")
                        this.getLogininforList()
                        this.$refs.tablePage.clearSelection()
                    }
                })
            })
        },

     
        // 导出
        exportWay() {
            this.download('logistics/driver/export', {
                ...this.searchData
            }, `司机信息_${new Date().getTime()}.xlsx`)
        },
        // 创建司机
        add() {
            this.isEdit = false;
            this.addVisile = true;
        },
        // 关联用户帐号模拟查询操作
        getAccountQueryListWay(query){
             beiGangApi.getAccountQueryList({phone:query}).then(res=>{
            
                if(res.code==200){
                    this.accountQueryList = res.data
                }
              
             })
        },
        
        handleAddSubmit() {
            // this.addVisile = false;
            this.$refs.dictForm.validate(valid => {
                if (valid) {

                    if (!this.isEdit) {
                        let obj = {
                            ...this.dictModel,
                            idCardPhotoFace: this.dictModel.idCardPhotoFace[0].url,
                            idCardPhotoBack: this.dictModel.idCardPhotoBack[0].url,
                            drivingLicensePhotoMain: this.dictModel.drivingLicensePhotoMain[0].url,
                            drivingLicensePhotoSecondary: this.dictModel.drivingLicensePhotoSecondary[0].url,

                        }
                        obj.isEnabled = this.dictModel.isEnabled == true ? 1 : 0
                        console.log(obj, 'params');

                        beiGangApi.addDriver(obj).then(res => {
                            if (!res.error) {
                                console.log('addDict', res);
                                this.dictModel = this.$options.data().dictModel
                                this.$message.success("添加司机成功")
                                this.addVisile = false;
                                this.accountQueryList = []
                                this.getLogininforList()
                            }
                        })
                    } else {
                        let obj = {
                            ...this.dictModel,
                            idCardPhotoFace: this.dictModel.idCardPhotoFace[0].url,
                            idCardPhotoBack: this.dictModel.idCardPhotoBack[0].url,
                            drivingLicensePhotoMain: this.dictModel.drivingLicensePhotoMain[0].url,
                            drivingLicensePhotoSecondary: this.dictModel.drivingLicensePhotoSecondary[0].url,

                        }
                        obj.isEnabled = this.dictModel.isEnabled == true ? 1 : 0
                        beiGangApi.updateDriver(obj).then(res => {
                            if (!res.error) {
                                console.log('editDict', res);
                                this.dictModel = this.$options.data().dictModel

                                this.$message.success("编辑司机成功")
                                this.addVisile = false;
                                this.accountQueryList = []
                                this.getLogininforList()
                            }
                        })
                    }
                } else {
                    this.$message.warning("请检查司机信息")
                    return false
                }
            })
        },
        handleAddCancle() {
            this.dictModel = this.$options.data().dictModel
            this.resetForm("dictForm")
            this.addVisile = false;
            this.accountQueryList = []
        },
        getLogininforList() {
            // addDateRange

            let { pageSize } = this.$refs.tablePage;
            let params = {

                ...this.searchModel,
                pageSize: pageSize,
                pageNum: this.currentPage


            }
            let obj = addDateRange(params, this.searchModel.createTime, 'createTime')
            delete obj.createTime
            let obj1 = addDateRange(obj, this.searchModel.updateTime, 'updateTime')
            delete obj1.updateTime


            console.log('====================================');
            console.log(obj1);
            console.log('====================================');
            // logininforList

            beiGangApi.driverList(obj1).then(res => {
                if (!res.error) {

                    this.total = res.total;
                    this.tableData = res.rows.map((item) => {
                        return {
                            ...item,
                            isEnabled: item.isEnabled + ''
                        }
                    })
                    // .map(item => {
                    //     return {
                    //         ...item,
                    //         // 审核按钮
                    //         canTakeAudit: (item.isCanTakeAudit && item.status == 1) || false
                    //     }
                    // });
                }
            })
        },
        selectable(row, index) {
            return true
            // if (row.status == 0) {
            //     return true
            // } else {
            //     return false
            // }
        },

        handleSearchSubmit() {
            this.currentPage = 1;
            this.getLogininforList()
        },
        handleSearchReset() {
            this.currentPage = 1;
            this.$refs.tablePage.clearSelection()
            this.getLogininforList()
        },
        handleSizeChange(v) {
            this.pageSize = v;
            this.currentPage = 1;
            this.getLogininforList()
        },
        handleCurrentChange(v) {
            this.currentPage = v;
            this.getLogininforList()
        },
        handleSelectionChange(v) {
            console.log('handleSelectionChange', v);
            this.selectArr = v
        },
        allot() {
            this.$modal.confirm('是否确认清空所有登录日志数据项？').then(function () {
                return cleanLogininfor();
            }).then(() => {
                this.getLogininforList();
                this.$modal.msgSuccess("清空成功");
            }).catch(() => { });
        },



        deleteCustomer() {
            if (this.selectArr.length == 0) {
                this.$message.warning("请先勾选日志")
                return
            }
            this.$confirm('确定删除吗', '删除', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {
                //   console.log('确认');
                let params = {
                    ids: this.selectArr.map(item => item.infoId),
                }
                delLogininfor(params.ids).then(res => {
                    if (!res.error) {
                        this.$message.success("操作成功")
                        this.getLogininforList()
                        this.$refs.tablePage.clearSelection()
                    }
                })
            })
        },
        gethtml(value) {
            if (value == null) {
                return;
            }
            var list = value.split(',');
            var resultStr = ""
            list.forEach(item => {
                if (item.includes("高") || item.includes("重要")) {
                    resultStr = resultStr + "<span style='color:#EE3333'>" + item + "</span>,";
                }
                else {
                    resultStr = resultStr + item + ",";
                }
            })
            if (resultStr != "") {
                return resultStr.slice(0, -1);
            }
        },


        handleSettingCancle() {
            this.settingVisile = false;
        },
        detailClose() {
            this.detailVisible = false;
            this.getLogininforList()
        },
        handleAllot() {
            this.allotVisile = true;
        },

        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    },
    destroyed() {
        this.$bus.$off('handleDetail')
        this.$bus.$off('handleDelete')
        this.$bus.$off('handleEdit')
    },
}
</script>
    
<style lang="scss" scoped>
.logLogin_block {

    // padding: 0 .2rem .2rem;
    .top {
        background-color: #fff;
        padding: 0 .3rem;
    }

    .bottom {
        .btn_area {
            margin-bottom: 0.2rem;
            margin-left: 0.3rem;
        }

        background-color: #fff;
        margin-top: 0.2rem;
        padding: 0.2rem 0rem;


    }




    .green {
        color: #2CAD00;
    }

    .orage {
        color: #EE7533;
    }

    .blue {
        color: #0076FF;
    }

    .red {
        color: #ff3333;
    }
}
</style>